<?php
class School extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return School the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'school';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
      array('list_email, post_school, monthly_tuition, ministry_gift, website, organization_email, church_email, owner_email, accredited_by, total_teachers1, total_teachers2, membership_extend', 'safe'),
			array('newsletter, user_id, membership_status, membership, hq, school_type, name, contact_person, principal_name_title, address, city, postal_code, province, phone, fax, email, principal_email, grade, full_time_teachers, part_time_teachers, goverment_teachers, diploma_teachers, s1_teachers, s2_teachers, s3_teachers, status, membership_sought, enrollment, founded, school_director, organization_name, organization_address, organization_phone, organization_fax, church_name, church_address, church_phone, church_fax, owner_name, owner_address, owner_phone, owner_fax, member_since, date_visited, needs1, needs2, needs3, pray1, pray2, pray3', 'safe'),
			//array('user_id, list_email, post_school', 'numerical', 'integerOnly'=>true),
			//array('membership_status, membership, hq, school_type, name, contact_person, principal_name_title, address, city, postal_code, province, phone, fax, email, principal_email, website, grade, full_time_teachers, part_time_teachers, goverment_teachers, diploma_teachers, s1_teachers, s2_teachers, s3_teachers, status, membership_sought, enrollment, founded, school_director, accredited_by, organization_name, organization_address, organization_phone, organization_fax, organization_email, church_name, church_address, church_phone, church_fax, church_email, owner_name, owner_address, owner_phone, owner_fax, owner_email, member_since, date_visited, needs1, needs2, needs3, pray1, pray2, pray3', 'length', 'max'=>1000),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, user_id, membership_status, membership, hq, school_type, name, contact_person, principal_name_title, address, city, postal_code, province, phone, fax, email, principal_email, website, grade, full_time_teachers, part_time_teachers, goverment_teachers, diploma_teachers, s1_teachers, s2_teachers, s3_teachers, status, membership_sought, enrollment, founded, school_director, list_email, post_school, accredited_by, organization_name, organization_address, organization_phone, organization_fax, organization_email, church_name, church_address, church_phone, church_fax, church_email, owner_name, owner_address, owner_phone, owner_fax, owner_email, member_since, date_visited, needs1, needs2, needs3, pray1, pray2, pray3', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
      'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'user_id' => 'User',
			'membership_status' => 'Membership Status',
			'membership' => 'Membership',
			'hq' => 'Hq',
			'school_type' => 'School Type',
			'name' => 'Name',
			'contact_person' => 'Contact Person',
			'principal_name_title' => 'Principal Name Title',
			'address' => 'Address',
			'city' => 'City',
			'postal_code' => 'Postal Code',
			'province' => 'Province',
			'phone' => 'Phone',
			'fax' => 'Fax',
			'email' => 'Email',
			'principal_email' => 'Principal Email',
			'website' => 'Website',
			'grade' => 'Grade',
			'full_time_teachers' => 'Full Time Teachers',
			'part_time_teachers' => 'Part Time Teachers',
			'goverment_teachers' => 'Goverment Teachers',
			'diploma_teachers' => 'Diploma Teachers',
			's1_teachers' => 'S1 Teachers',
			's2_teachers' => 'S2 Teachers',
			's3_teachers' => 'S3 Teachers',
			'status' => 'Status',
			'membership_sought' => 'Membership Sought',
			'enrollment' => 'Enrollment',
			'founded' => 'Founded',
			'school_director' => 'School Director',
			'list_email' => 'List Email',
			'post_school' => 'Post School',
			'accredited_by' => 'Accredited By',
			'organization_name' => 'Organization Name',
			'organization_address' => 'Organization Address',
			'organization_phone' => 'Organization Phone',
			'organization_fax' => 'Organization Fax',
			'organization_email' => 'Organization Email',
			'church_name' => 'Church Name',
			'church_address' => 'Church Address',
			'church_phone' => 'Church Phone',
			'church_fax' => 'Church Fax',
			'church_email' => 'Church Email',
			'owner_name' => 'Owner Name',
			'owner_address' => 'Owner Address',
			'owner_phone' => 'Owner Phone',
			'owner_fax' => 'Owner Fax',
			'owner_email' => 'Owner Email',
			'member_since' => 'Member Since',
			'date_visited' => 'Date Visited',
			'needs1' => 'Needs1',
			'needs2' => 'Needs2',
			'needs3' => 'Needs3',
			'pray1' => 'Pray1',
			'pray2' => 'Pray2',
			'pray3' => 'Pray3',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('membership_status',$this->membership_status,true);
		$criteria->compare('membership',$this->membership,true);
		$criteria->compare('hq',$this->hq,true);
		$criteria->compare('school_type',$this->school_type,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('contact_person',$this->contact_person,true);
		$criteria->compare('principal_name_title',$this->principal_name_title,true);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('postal_code',$this->postal_code,true);
		$criteria->compare('province',$this->province,true);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('fax',$this->fax,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('principal_email',$this->principal_email,true);
		$criteria->compare('website',$this->website,true);
		$criteria->compare('grade',$this->grade,true);
		$criteria->compare('full_time_teachers',$this->full_time_teachers,true);
		$criteria->compare('part_time_teachers',$this->part_time_teachers,true);
		$criteria->compare('goverment_teachers',$this->goverment_teachers,true);
		$criteria->compare('diploma_teachers',$this->diploma_teachers,true);
		$criteria->compare('s1_teachers',$this->s1_teachers,true);
		$criteria->compare('s2_teachers',$this->s2_teachers,true);
		$criteria->compare('s3_teachers',$this->s3_teachers,true);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('membership_sought',$this->membership_sought,true);
		$criteria->compare('enrollment',$this->enrollment,true);
		$criteria->compare('founded',$this->founded,true);
		$criteria->compare('school_director',$this->school_director,true);
		$criteria->compare('list_email',$this->list_email);
		$criteria->compare('post_school',$this->post_school);
		$criteria->compare('accredited_by',$this->accredited_by,true);
		$criteria->compare('organization_name',$this->organization_name,true);
		$criteria->compare('organization_address',$this->organization_address,true);
		$criteria->compare('organization_phone',$this->organization_phone,true);
		$criteria->compare('organization_fax',$this->organization_fax,true);
		$criteria->compare('organization_email',$this->organization_email,true);
		$criteria->compare('church_name',$this->church_name,true);
		$criteria->compare('church_address',$this->church_address,true);
		$criteria->compare('church_phone',$this->church_phone,true);
		$criteria->compare('church_fax',$this->church_fax,true);
		$criteria->compare('church_email',$this->church_email,true);
		$criteria->compare('owner_name',$this->owner_name,true);
		$criteria->compare('owner_address',$this->owner_address,true);
		$criteria->compare('owner_phone',$this->owner_phone,true);
		$criteria->compare('owner_fax',$this->owner_fax,true);
		$criteria->compare('owner_email',$this->owner_email,true);
		$criteria->compare('member_since',$this->member_since,true);
		$criteria->compare('date_visited',$this->date_visited,true);
		$criteria->compare('needs1',$this->needs1,true);
		$criteria->compare('needs2',$this->needs2,true);
		$criteria->compare('needs3',$this->needs3,true);
		$criteria->compare('pray1',$this->pray1,true);
		$criteria->compare('pray2',$this->pray2,true);
		$criteria->compare('pray3',$this->pray3,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}

  public function makeMemberSchool($user_info, $school_info, $school_data, $flag, $school_type){
    // change this to true/false to debug without sending email
    $debug_mode = true;

    // set current year
    $date = date('Y');
    $str_date = substr((string)$date, -2);
    
    // echo $date;
    // echo $str_date;

    $user = new Users('create');
    $user->attributes=$school_info;
    $user->attributes=$user_info;
    $user->school_name = $school_info['name'];
    $user->email = $user_info['email'];
    $user->name = $school_data['principal_name_title'];

    // generate password
    for($code_length = 10, $newcode = ''; strlen($newcode) < $code_length; $newcode .= chr(!rand(0, 2) ? rand(48, 57) : (!rand(0, 1) ? rand(65, 90) : rand(97, 122))));

    $user->password = md5($newcode);
    $user->password_salt = $newcode;

    //generate username
    $criteria = new CDbCriteria;
    $criteria -> order = 'id DESC';
    $criteria -> limit = 1;

    $tmp = School::model()->find($criteria);
    $str = explode("/", $tmp->membership);
    //$user->username = ((int)$str[3]+1);

    $user->save('create');

    $school = new School;
    $school->user_id = $user->id;
    $school->attributes = $school_info;
    $school->member_since = (string)$date;
    $school->date_visited = $school_info['date_visited'];
    
    $newsletter = '';
    if(isset($_POST['newsletter'])){
      $newsletter = $_POST['newsletter']['email'];
    }
    $school->newsletter = $_POST['info']['newsletter1']. ' '. $newsletter. '& '. $_POST['info']['newsletter2'];
    
    $school->ministry_gift = $school_info['gift_value'];
    $school->monthly_tuition = $school_info['monthly_tuition'];

    $type= '';
    $extend = 0;
    if(isset($school_info['membership_status']))
    {
      if($school_info['membership_status'] == 'International - 1 Year'){
        $school->membership_status = 'International';
        $type = 'ID-I';
      }else{
        $school->membership_status = 'National';
        $type = 'ID';
      }

      if($school_info['membership_status'] == 'International - 1 Year' || $school_info['membership_status'] == 'National - 1 Year'){
        $extend = 1;
      }
      else{
        $extend = 2;
      }

      $school->membership_extend = $extend;
    }

    // $school->membership = $type.'/'.$flag.'/'.$str_date.'/'.((int)$str[3]+1).'/tmp';
    $school->membership = $type.'/'.$flag.'/'.$str_date.'/'.((int)$str[3]+1);

    $school->attributes = $school_data;
    $school->membership_sought = $school_info['membership_status'];
    $school->principal_email = $school_data['principal_email'];
    $school->school_type = $school_type;
    
    $tmp = '';
    $total = count($school_data['students']);
    
    // insert all students into database
    $fl = '';
    $fp = '';
    
    for($a=1;$a<=$total;$a++){
      if($a<$total){
        $tmp = $school_data['students'][$a].','.$tmp;
      }
      else{
        $tmp = $tmp.$school_data['students'][$a];
      }
      
      // flag for determine kindergarten / playgroup
      if($school_type == 'Kindergarten'){
        if($a == 1 || $a == 2){
          if($school_data['students'][$a] > 0){ $fl = 'Kindergarten'; }
        }else if($a == 3 || $a == 4){
          if($school_data['students'][$a] > 0){ $fp = 'Playgroup'; }
        }
      }
    }
    
    $school->students = $tmp;
    
    // determine school type and concat it with school name
    if($fp != ''){ $fl = $fl.' & '.$fp; }
    
    $school->name = $school->name.', '.$fl;
    
    $school->save();
    
    // expired date
    $user->expired_date = ((int)$school->membership_extend + (int)$school->member_since).'-08-31';    
    $user->save();
    
    // save into history log
    $history = new SchoolHistory;
    $history->school_id = $school->id;
    $history->year = $school->founded;
    $history->school_status = $school->school_type;
    $history->membership_sought = $school->membership_sought;
    $history->monthly_tuition = $school->monthly_tuition;
    $history->total_students = $school->enrollment;
    $history->ministries_gift = $school->ministry_gift;
    $history->total_payment = $user->membership_fee;
    $history->save();

    if($debug_mode == false){
    // send email
    $email = Yii::app()->email;
    $email->to = $user->email;
    $email->subject = 'ACSI - Thank you for registering with us';
    $email->message = 'Please wait for further confirmation notice from us.';
    $email->send();
    }

    // $folder=Yii::getPathOfAlias('webroot.assets.users').DIRECTORY_SEPARATOR;
    // mkdir($folder.$user->id);
  }
  
  public function updateMemberSchool($user_info, $school_info, $school_data, $flag, $school_type){

    // set current year
    $date = date('Y');
    $str_date = substr((string)$date, -2);
    
    $user = Users::model()->find('id = :id', array(':id' => $_SESSION['id']));
    $user->attributes=$school_info;
    $user->attributes=$user_info;
    $user->school_name = $school_info['name'];
    $user->email = $school_data['principal_email'];
    $user->name = $school_data['principal_name_title'];

    $criteria = new CDbCriteria;
    $criteria -> order = 'id DESC';
    $criteria -> limit = 1;

    $tmp = School::model()->find($criteria);
    $str = explode("/", $tmp->membership);
    $user->save();

    $school = School::model()->find('user_id = :user_id', array(':user_id' => $user->id));
    $school->user_id = $user->id;
    $school->attributes = $school_info;
    $school->member_since = (string)$date;
    $school->date_visited = $school_info['date_visited'];
    
    $newsletter = '';
    if(isset($_POST['newsletter'])){
      $newsletter = $_POST['newsletter']['email'];
    }
    $school->newsletter = $_POST['info']['newsletter1']. ' '. $newsletter. '& '. $_POST['info']['newsletter2'];
    
    $school->ministry_gift = $school_info['gift_value'];
    $school->monthly_tuition = $school_info['monthly_tuition'];

    $type= '';
    $extend = 0;
    if(isset($school_info['membership_status']))
    {
      if($school_info['membership_status'] == 'International - 1 Year'){
        $school->membership_status = 'International';
        $type = 'ID-I';
      }else{
        $school->membership_status = 'National';
        $type = 'ID';
      }

      if($school_info['membership_status'] == 'International - 1 Year' || $school_info['membership_status'] == 'National - 1 Year'){
        $extend = 1;
      }
      else{
        $extend = 2;
      }

      $school->membership_extend = $extend;
    }

    $school->membership = $type.'/'.$flag.'/'.$str_date.'/'.((int)$str[3]+1).'/tmp';

    $school->attributes = $school_data;
    $school->membership_sought = $school_info['membership_status'];
    $school->school_type = $school_type;
    
    $tmp = '';
    $total = count($school_data['students']);
    
    for($a=1;$a<=$total;$a++){
      if($a<$total){
        $tmp = $school_data['students'][$a].','.$tmp;
      }
      else{
        $tmp = $tmp.$school_data['students'][$a];
      }
    }
    
    $school->students = $tmp;
    // print_r($total);
    
    $school->save();

    // save into history log
    $history = new SchoolHistory;
    $history->school_id = $school->id;
    $history->year = $school->founded;
    $history->school_status = $school->school_type;
    $history->membership_sought = $school->membership_sought;
    $history->monthly_tuition = $school->monthly_tuition;
    $history->total_students = $school->enrollment;
    $history->ministries_gift = $school->ministry_gift;
    $history->total_payment = $user->membership_fee;
    $history->save();
    
    // create invoice
    $related_schools = Users::model()->findAll('school_name = :school_name AND city = :city AND address = :address', array(':school_name' => $user->school_name, ':city' => $user->city, ':address' => $user->address));
    
    foreach($related_schools as $user){
      $invoice = new Invoices;
      $invoice->user_id = $user->id;
      $invoice->school_status = $school->membership_status;
      $invoice->membership_sought = $school->membership_sought;
      
      $tuition = "";
      if($school->membership_sought == 1){
        $tuition = "less than Rp. 200.000,-";
      }else if($school->membership_sought == 2){
        $tuition = "Rp. 200.000 - Rp. 500.00";
      }else{
        $tuition = "more than Rp. 500.000,-";
      }
      
      $invoice->monthly_tuition = $tuition;
      $invoice->students = $school->enrollment;
      $invoice->ministry_gift = $school->ministry_gift;
      $invoice->total_payment = $user->membership_fee;
      
      $invoice->save();
    }

    // $folder=Yii::getPathOfAlias('webroot.assets.users').DIRECTORY_SEPARATOR;
    // mkdir($folder.$user->id);
  }
}